// 1. 加载 express 模块
var express = require('express');
// 2. 创建一个 app 对象（类似于创建一个 server 对象）
var app = express();
//解析POST请求需要安装此依赖
//extended为false表示使用querystring来解析数据，这是URL-encoded解析器
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
// 3. 启动服务
app.listen(8082, function() {
    console.log('http://localhost:8082');
});
app.all('*', (req, res, next) => {
    console.log("-----all------");
    res.setHeader("Access-Control-Allow-Origin", "*");
    next();
})
const mysql = require('mysql');
const querySql = (sql, sqlParam, callback) => {
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'book'
    });
    connection.connect();
    connection.query(sql, sqlParam, function(err, result) {
        callback(err, result)
    });
    connection.end();
}
const resultData = {
    code: '',
    msg: '',
    data: []
}
app.post('/books/query', (req, res) => {
    let sql = '';
    let sqlParam = [];
    // sqlParam = [req.body.name];
    // sql = 'select * from books where name = ?'
    if (req.body.name) {
        sqlParam = [req.body.name];
        sql = 'select * from books where name = ?'
    } else {
        sql = 'select * from books'
    }


    //内部函数变量是就近取值
    querySql(sql, sqlParam, (err, result) => {
        if (err) {
            console.log("------------", err);
            res.send(err)
        } else {
            resultData.code = '2000';
            resultData.msg = "查询成功"
            resultData.data = result
            res.send(resultData)
        }
    })
})
app.post('/books/add', (req, res) => {
    let sql = 'insert into books (name,author,price) values(?,?,?)';
    let sqlParam = [req.body.name, req.body.author, req.body.price];
    //内部函数变量是就近取值
    querySql(sql, sqlParam, (err, result) => {
        if (err) {
            console.log("------------", err);
            res.send(err)
        } else {
            res.send(result)
        }
    })
})
app.post('/books/updateById', (req, res) => {
    let sql = 'update books set name=?, price=?,author=? where id =?';
    let sqlParam = [req.body.name, req.body.price, req.body.author, req.body.id];
    //内部函数变量是就近取值
    querySql(sql, sqlParam, (err, result) => {
        if (err) {
            console.log("------------", err);
            res.send(err)
        } else {
            res.send(result)
        }
    })
})

app.get('/books/delById', (req, res) => {
    let sql = "delete from books where id = ?"
    let sqlParam = [req.query.id];
    querySql(sql, sqlParam, (err, result) => {
        if (err) {
            console.log("------------", err);
            res.send(err)
        } else {
            console.log(result);
            if (result.affectedRows == 1) {
                resultData.code = '2000';
                resultData.msg = "删除成功"
            } else {
                resultData.code = '5000';
                resultData.msg = "删除失败"
            }
            res.send(resultData)
        }
    })
})
app.get('/books/getById', (req, res) => {
    let sql = "select * from books where id = ?"
    let sqlParam = [req.query.id];
    querySql(sql, sqlParam, (err, result) => {
        if (err) {
            console.log("------------", err);
            res.send(err)
        } else {
            res.send(result)
        }
    })
})